﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Xml.Serialization;
using System.IO;
using System.Xml.Linq;

namespace INdTFramework.Extensions
{
    public static class StringUtils
    {
        private static readonly Regex QueryStringRegex = new Regex(@"[\?&](?<name>[^&=]+)=(?<value>[^&=]+)");
        private static readonly Regex StringRegex = new Regex(@"[\a-zA-Z](?<name>[^&=]+)=(?<value>[^&=]+)");

        public static IEnumerable<KeyValuePair<string, string>> SelectParams(this Uri value)
        {
            string strUri = value.Query.ToString();

            var matches = QueryStringRegex.Matches(strUri);
            for (var i = 0; i < matches.Count; i++)
            {
                var match = matches[i];
                yield return new KeyValuePair<string, string>(match.Groups["name"].Value, match.Groups["value"].Value);
            }
        }

        public static IEnumerable<KeyValuePair<string, string>> SelectParams(this string strUri)
        {
            String[] splitArray = strUri.Split('&');

            foreach (var s in splitArray)
            {
                String[] kv = s.Split('=');
                yield return new KeyValuePair<string, string>(kv[0], kv[1]);
            }
        }

        public static string GetParamenter(this Uri value, string parameterName)
        {
            IEnumerable<KeyValuePair<string, string>> oParams = value.SelectParams();
            return (from p in oParams
                    where p.Key == parameterName
                        select p.Value).SingleOrDefault();
        }

        public static string GetParamenter(this String value, string parameterName)
        {
            IEnumerable<KeyValuePair<string, string>> oParams = value.SelectParams();
            return (from p in oParams
                    where p.Key == parameterName
                    select p.Value).SingleOrDefault();
        }

        public static string SerializeToString(this XmlSerializer value, Object data)
        {
            using (StringWriter writer = new StringWriter())
            {
                value.Serialize(writer, data);
                return writer.ToString();
            }
        }

        public static T DeserializeFromString<T>(this XmlSerializer serializer, String json)
        {
            XDocument document = XDocument.Parse(json);
            return (T)serializer.Deserialize(document.CreateReader());
        }
    }
}
